﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using NFinal.Middleware.Resources.Helper;

namespace NFinal.Middleware.Resources
{
    public delegate Task InvokeDelegate<TContext>(TContext context);
    public class ResourcesMiddleware<TContext>
    {
        private string defaultUrl;
        private string accessControlAllowOrigin;
        private readonly InvokeDelegate<TContext> next;
        private Resources[] ResourcesArray;
        public ResourcesMiddleware(InvokeDelegate<TContext> next, ResourcesConfig config)
        {
            this.ResourcesArray = config.ResourcesArray;
            this.accessControlAllowOrigin = config.accessControlAllowOrigin;
            if (config.defaultUrl == null)
            {
                this.defaultUrl = "/";
            }
            else
            {
                this.defaultUrl = config.defaultUrl;
            }
            foreach (var resources in this.ResourcesArray)
            {
                ResourcesReader resourcesReader=new ResourcesReader(resources.assembly);
                resourcesReader.ReadToMemory(resources);
            }
            this.next = next;
        }
        public async Task Invoke(TContext context)
        {
            string requestPath = GetRequestPath(context);
            if (requestPath.StartsWith("/"))
            {
                if (requestPath.Length == 1)
                {
                    requestPath = defaultUrl;
                }
                if (ResourcesReader.sortedDictionary.TryGetValue(requestPath, out SimpleResponse response))
                {
                    if (accessControlAllowOrigin != null)
                    {
                        AddOrUpdateHeader(context, "Access-Control-Allow-Origin", new string[] { accessControlAllowOrigin });
                    }
                    AddOrUpdateHeader(context,"Content-Type",new string[]{response.contentType});
                    SetStatusCode(context, 200);
                    Stream body = GetResponseStream(context);
                    await body.WriteAsync(response.content, 0, response.content.Length);
                }
                else
                {
                    await next(context);
                }
            }
            else
            {
                await next(context);
            }
        }
        public virtual string GetRequestPath(TContext context)
        {
            throw new NotImplementedException();
        }
        public virtual void AddOrUpdateHeader(TContext context, string key, string[] value)
        {
            throw new NotImplementedException();
        }
        public virtual void SetStatusCode(TContext context, int statusCode)
        {
            throw new NotImplementedException();
        }
        public virtual Stream GetResponseStream(TContext context)
        {
            throw new NotImplementedException();
        }
    }
}
